using Gtk;
using Serpis;
using System;
using System.Reflection;

namespace PArticulo
{
	[System.ComponentModel.ToolboxItem(true)]
	public partial class DBVisor : Gtk.Bin
	{
		private string commandText;
		
		public DBVisor (string consulta)
		{
			this.Build();
			
			commandText= consulta;
			
			miTreeView.Init(AppDbConnection.Instance.DbConnection, commandText);
			
			editAction.Activated += delegate 
			{
				long id = Convert.ToInt64(miTreeView.GetValue(0));
				
				IPersister persister = PersisterFactory.NewPersister(typeof(Articulo));
				
				Articulo articulo = (Articulo)persister.Load(typeof(Articulo), id);
					
				ArticuloView articuloView = new ArticuloView();
				
				Controller controller = new Controller(articulo, articuloView);
				controller.Refresh();
				
				articuloView.SaveAction.Activated += delegate {
					controller.Update();
					
					foreach (PropertyInfo propertyInfo in articulo.GetType().GetProperties())
						Console.WriteLine("{0}={1}", propertyInfo.Name, propertyInfo.GetValue(articulo, null));
					
					articuloView.Destroy();
					
					persister.Save(articulo);
					
					miTreeView.Refresh();
				};
			};
			
			deleteAction.Activated += delegate 
			{
				MessageDialog messageDialog= new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, "¿Quiere eliminar el elemento seleccionado");
//				
				int response= messageDialog.Run();
				messageDialog.Destroy();
				
				if(response != (int)ResponseType.Yes)
					return;
					
				IPersister persister= PersisterFactory.NewPersister(typeof(Articulo));
			
				try {
					persister.Delete(typeof(Articulo), Convert.ToInt64(miTreeView.GetValue(0)));
				}
				catch(Exception e) {
					messageDialog= new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, e.Message);
					messageDialog.Run();
					messageDialog.Destroy();
				}
				
				miTreeView.Refresh();
			};
		}
	}
}

